package com.situ.springboot.interceptor;

import com.situ.springboot.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 拦截器能实现，浏览器请求服务器的所有请求首先经过拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        // session.setAttribute("user", user);
        // 从session里面拿出user到底有没有来判断用户有没有登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 用户没有登录，跳转到登录界面
            response.sendRedirect(request.getContextPath() + "/user/getLoginPage");
            return  false;
        } else {
            // 已经登录，return true代表可以访问后面的请求
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
